package code11_io.字节流;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author 黄衡熙
 * @version 1.0
 */
public class Test03_字节数组流 {

    public static void main(String[] args) {
        test02();
    }

    public static void test01() {
        // 准备一个byte数组,用于读取内容
        byte[] data = "Hello World".getBytes();
        try (
                InputStream in = new ByteArrayInputStream(data);
        ) {
            byte[] b = new byte[1024];
            int i = -1;
            while ((i = in.read(b)) != -1) {
                System.out.println(new String(b, 0, i));
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void test02() {
        try (
                ByteArrayOutputStream out = new ByteArrayOutputStream();
        ) {
            out.write("你好 世界".getBytes());
            out.flush();

            // 获取内置的字节数组的数据
            byte[] data = out.toByteArray();
            // 从内存中读取数据
            System.out.println(new String(data));

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}